"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { DatePickerWithRange } from "@/components/date-range-picker"
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"
import { DownloadIcon, FilterIcon, RefreshCwIcon, LineChartIcon, BarChartIcon, TableIcon } from "lucide-react"
import {
  LineChart,
  Line,
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts"
import DashboardLayout from "@/components/dashboard-layout"

// 模拟数据
const mockSensorData = Array.from({ length: 30 }, (_, i) => ({
  date: `2025-05-${(i + 1).toString().padStart(2, "0")}`,
  moisture: 25 + Math.random() * 10,
  temperature: 20 + Math.random() * 8,
  ec: 1.2 + Math.random() * 0.8,
  ph: 6.5 + Math.random() * 1,
}))

const mockIrrigationData = [
  { date: "2025-05-01", amount: 25, duration: 45, fertilizer: 15 },
  { date: "2025-05-04", amount: 20, duration: 35, fertilizer: 12 },
  { date: "2025-05-07", amount: 15, duration: 30, fertilizer: 10 },
  { date: "2025-05-10", amount: 25, duration: 45, fertilizer: 15 },
  { date: "2025-05-13", amount: 20, duration: 35, fertilizer: 12 },
  { date: "2025-05-16", amount: 15, duration: 30, fertilizer: 10 },
]

const sensorTypes = [
  { value: "moisture", label: "土壤湿度" },
  { value: "temperature", label: "土壤温度" },
  { value: "ec", label: "EC值" },
  { value: "ph", label: "PH值" },
]

const locations = [
  { value: "all", label: "全部位置" },
  { value: "1号农田", label: "1号农田" },
  { value: "2号农田", label: "2号农田" },
]

export default function DataPage() {
  const [selectedSensor, setSelectedSensor] = useState("moisture")
  const [selectedLocation, setSelectedLocation] = useState("all")
  const [dateRange, setDateRange] = useState({
    from: new Date(2025, 4, 1),
    to: new Date(2025, 4, 30),
  })

  const chartData = mockSensorData.map((item) => ({
    date: item.date.substring(5), // 只显示月-日
    value: item[selectedSensor],
  }))

  const getChartTitle = () => {
    switch (selectedSensor) {
      case "moisture":
        return "土壤湿度 (%)"
      case "temperature":
        return "土壤温度 (°C)"
      case "ec":
        return "EC值 (mS/cm)"
      case "ph":
        return "PH值"
      default:
        return ""
    }
  }

  const getChartColor = () => {
    switch (selectedSensor) {
      case "moisture":
        return "#3b82f6" // blue
      case "temperature":
        return "#ef4444" // red
      case "ec":
        return "#8b5cf6" // purple
      case "ph":
        return "#22c55e" // green
      default:
        return "#3b82f6"
    }
  }

  return (
    <DashboardLayout>
      <div className="p-6 space-y-6">
        <div className="flex justify-between items-center">
          <h1 className="text-2xl font-bold">历史数据分析</h1>
          <div className="flex gap-2">
            <Button variant="outline" size="sm">
              <DownloadIcon className="h-4 w-4 mr-2" />
              导出数据
            </Button>
            <Button variant="outline" size="sm">
              <RefreshCwIcon className="h-4 w-4 mr-2" />
              刷新
            </Button>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>数据筛选</CardTitle>
            <CardDescription>选择时间范围和数据类型进行查询</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="flex flex-col md:flex-row gap-4">
              <div className="flex-1">
                <Label htmlFor="date-range" className="mb-2 block">
                  时间范围
                </Label>
                <DatePickerWithRange id="date-range" date={dateRange} setDate={setDateRange} />
              </div>
              <div>
                <Label htmlFor="sensor-type" className="mb-2 block">
                  数据类型
                </Label>
                <Select value={selectedSensor} onValueChange={setSelectedSensor}>
                  <SelectTrigger id="sensor-type" className="w-[180px]">
                    <SelectValue placeholder="选择数据类型" />
                  </SelectTrigger>
                  <SelectContent>
                    {sensorTypes.map((type) => (
                      <SelectItem key={type.value} value={type.value}>
                        {type.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div>
                <Label htmlFor="location" className="mb-2 block">
                  位置
                </Label>
                <Select value={selectedLocation} onValueChange={setSelectedLocation}>
                  <SelectTrigger id="location" className="w-[180px]">
                    <SelectValue placeholder="选择位置" />
                  </SelectTrigger>
                  <SelectContent>
                    {locations.map((location) => (
                      <SelectItem key={location.value} value={location.value}>
                        {location.label}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
              <div className="flex items-end">
                <Button>
                  <FilterIcon className="h-4 w-4 mr-2" />
                  应用筛选
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          <Card className="lg:col-span-2">
            <CardHeader>
              <CardTitle>传感器数据趋势</CardTitle>
              <CardDescription>查看选定时间范围内的数据变化趋势</CardDescription>
            </CardHeader>
            <CardContent>
              <Tabs defaultValue="line">
                <div className="flex justify-between items-center mb-4">
                  <TabsList>
                    <TabsTrigger value="line">
                      <LineChartIcon className="h-4 w-4 mr-2" />
                      折线图
                    </TabsTrigger>
                    <TabsTrigger value="bar">
                      <BarChartIcon className="h-4 w-4 mr-2" />
                      柱状图
                    </TabsTrigger>
                    <TabsTrigger value="table">
                      <TableIcon className="h-4 w-4 mr-2" />
                      表格
                    </TabsTrigger>
                  </TabsList>
                  <div className="text-sm font-medium text-gray-500">{getChartTitle()}</div>
                </div>

                <TabsContent value="line">
                  <div className="h-[400px]">
                    <ResponsiveContainer width="100%" height="100%">
                      <LineChart data={chartData}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="date" />
                        <YAxis />
                        <Tooltip />
                        <Legend />
                        <Line
                          type="monotone"
                          dataKey="value"
                          stroke={getChartColor()}
                          name={getChartTitle()}
                          strokeWidth={2}
                        />
                      </LineChart>
                    </ResponsiveContainer>
                  </div>
                </TabsContent>

                <TabsContent value="bar">
                  <div className="h-[400px]">
                    <ResponsiveContainer width="100%" height="100%">
                      <BarChart data={chartData}>
                        <CartesianGrid strokeDasharray="3 3" />
                        <XAxis dataKey="date" />
                        <YAxis />
                        <Tooltip />
                        <Legend />
                        <Bar dataKey="value" fill={getChartColor()} name={getChartTitle()} />
                      </BarChart>
                    </ResponsiveContainer>
                  </div>
                </TabsContent>

                <TabsContent value="table">
                  <div className="rounded-md border max-h-[400px] overflow-auto">
                    <Table>
                      <TableHeader>
                        <TableRow>
                          <TableHead>日期</TableHead>
                          <TableHead>土壤湿度 (%)</TableHead>
                          <TableHead>土壤温度 (°C)</TableHead>
                          <TableHead>EC值 (mS/cm)</TableHead>
                          <TableHead>PH值</TableHead>
                        </TableRow>
                      </TableHeader>
                      <TableBody>
                        {mockSensorData.map((item, index) => (
                          <TableRow key={index}>
                            <TableCell>{item.date}</TableCell>
                            <TableCell>{item.moisture.toFixed(1)}</TableCell>
                            <TableCell>{item.temperature.toFixed(1)}</TableCell>
                            <TableCell>{item.ec.toFixed(2)}</TableCell>
                            <TableCell>{item.ph.toFixed(1)}</TableCell>
                          </TableRow>
                        ))}
                      </TableBody>
                    </Table>
                  </div>
                </TabsContent>
              </Tabs>
            </CardContent>
          </Card>

          <div className="space-y-6">
            <Card>
              <CardHeader>
                <CardTitle>数据统计</CardTitle>
                <CardDescription>选定时间范围内的数据统计</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="grid grid-cols-2 gap-4">
                    <div className="bg-blue-50 p-3 rounded-lg">
                      <p className="text-xs text-gray-500">平均值</p>
                      <p className="text-xl font-bold text-blue-700">
                        {(chartData.reduce((sum, item) => sum + item.value, 0) / chartData.length).toFixed(2)}
                      </p>
                    </div>
                    <div className="bg-green-50 p-3 rounded-lg">
                      <p className="text-xs text-gray-500">最大值</p>
                      <p className="text-xl font-bold text-green-700">
                        {Math.max(...chartData.map((item) => item.value)).toFixed(2)}
                      </p>
                    </div>
                    <div className="bg-amber-50 p-3 rounded-lg">
                      <p className="text-xs text-gray-500">最小值</p>
                      <p className="text-xl font-bold text-amber-700">
                        {Math.min(...chartData.map((item) => item.value)).toFixed(2)}
                      </p>
                    </div>
                    <div className="bg-purple-50 p-3 rounded-lg">
                      <p className="text-xs text-gray-500">标准差</p>
                      <p className="text-xl font-bold text-purple-700">
                        {Math.sqrt(
                          chartData.reduce(
                            (sum, item) =>
                              sum +
                              Math.pow(item.value - chartData.reduce((s, i) => s + i.value, 0) / chartData.length, 2),
                            0,
                          ) / chartData.length,
                        ).toFixed(2)}
                      </p>
                    </div>
                  </div>

                  <div className="pt-2">
                    <h3 className="text-sm font-medium mb-2">数据分布</h3>
                    <div className="h-[150px]">
                      <ResponsiveContainer width="100%" height="100%">
                        <BarChart
                          data={[
                            { range: "<25", count: chartData.filter((i) => i.value < 25).length },
                            { range: "25-30", count: chartData.filter((i) => i.value >= 25 && i.value < 30).length },
                            { range: "30-35", count: chartData.filter((i) => i.value >= 30 && i.value < 35).length },
                            { range: ">35", count: chartData.filter((i) => i.value >= 35).length },
                          ]}
                        >
                          <CartesianGrid strokeDasharray="3 3" />
                          <XAxis dataKey="range" />
                          <YAxis />
                          <Tooltip />
                          <Bar dataKey="count" fill={getChartColor()} />
                        </BarChart>
                      </ResponsiveContainer>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>灌溉记录</CardTitle>
                <CardDescription>选定时间范围内的灌溉活动</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="rounded-md border">
                  <Table>
                    <TableHeader>
                      <TableRow>
                        <TableHead>日期</TableHead>
                        <TableHead>水量 (mm)</TableHead>
                        <TableHead>时长 (分钟)</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {mockIrrigationData.map((item, index) => (
                        <TableRow key={index}>
                          <TableCell>{item.date}</TableCell>
                          <TableCell>{item.amount}</TableCell>
                          <TableCell>{item.duration}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </CardContent>
            </Card>
          </div>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>多参数对比分析</CardTitle>
            <CardDescription>比较不同参数之间的关系</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="h-[400px]">
              <ResponsiveContainer width="100%" height="100%">
                <LineChart data={mockSensorData}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="date" tickFormatter={(value) => value.substring(5)} />
                  <YAxis yAxisId="left" />
                  <YAxis yAxisId="right" orientation="right" domain={[5, 8]} />
                  <Tooltip />
                  <Legend />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="moisture"
                    stroke="#3b82f6"
                    name="土壤湿度 (%)"
                    strokeWidth={2}
                  />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="temperature"
                    stroke="#ef4444"
                    name="土壤温度 (°C)"
                    strokeWidth={2}
                  />
                  <Line
                    yAxisId="left"
                    type="monotone"
                    dataKey="ec"
                    stroke="#8b5cf6"
                    name="EC值 (mS/cm)"
                    strokeWidth={2}
                  />
                  <Line yAxisId="right" type="monotone" dataKey="ph" stroke="#22c55e" name="PH值" strokeWidth={2} />
                </LineChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-4 text-sm text-gray-500">
              <p>通过多参数对比分析，可以发现不同环境因素之间的相关性，为灌溉决策提供依据。</p>
            </div>
          </CardContent>
        </Card>
      </div>
    </DashboardLayout>
  )
}
